#include "communitypage.h"
#include "ui_communitypage.h"
#include "util/messagebox.h"
#include <QClipboard>
#include <QApplication>
#include <QDesktopServices>
#include <QScrollArea>
#include <QVBoxLayout>
#include <QSpacerItem>

namespace WordMemory
{
    CommunityPage::CommunityPage(QWidget *parent)
        : QWidget(parent)
        , ui(new Ui::CommunityPage)
        , serverhelper(new ServerHelper(this))

        , postsLayout(nullptr)
    {

        ui->setupUi(this);
        setupUi();
        setupConnections();
        loadPosts();
    }

    CommunityPage::~CommunityPage()
    {
        clearPostsLayout();
        if(ui) delete ui;
    }

    void CommunityPage::refreshPageData()
    {
        loadPosts();
    }

    void CommunityPage::setupUi()
    {
        if (!ui->scrollAreaWidgetContents->layout())
        {
            postsLayout = new QVBoxLayout(ui->scrollAreaWidgetContents);
            postsLayout->setSpacing(10);
            postsLayout->setAlignment(Qt::AlignTop);
            postsLayout->setContentsMargins(5,5,5,5);
            ui->scrollAreaWidgetContents->setLayout(postsLayout);
        }
        else
        {
            postsLayout = qobject_cast<QVBoxLayout*>(ui->scrollAreaWidgetContents->layout());
        }

        ui->postsScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    }


    void CommunityPage::setupConnections()
    {
        connect(serverhelper, &ServerHelper::getCommunityPostsFinished, this, &CommunityPage::onGetCommunityPostsFinished);
        connect(serverhelper, &ServerHelper::toggleLikePostFinished, this, &CommunityPage::onToggleLikePostFinished);
        connect(serverhelper, &ServerHelper::recordSharePostFinished, this, &CommunityPage::onRecordSharePostFinished);
    }

    void CommunityPage::loadPosts()
    {
        if (!UserManager::instance().isLoggedIn())
        {
            clearPostsLayout();

            QLabel* loginMsg = new QLabel("请先登录查看社区内容。");
            loginMsg->setAlignment(Qt::AlignCenter);
            loginMsg->setStyleSheet("font-size: 16px; color: #777; margin-top: 50px;");
            postsLayout->addWidget(loginMsg);
            return;
        }

        int currentUserId = UserManager::instance().getUserId();
        serverhelper->getCommunityPosts(currentUserId);
    }

    void CommunityPage::clearPostsLayout()
    {
        postCardMap.clear();
        if (!postsLayout) return;
        QLayoutItem* item;

        while ((item = postsLayout->takeAt(0)) != nullptr)
        {
            if (item->widget()) {
                item->widget()->deleteLater();
            }
            delete item;
        }
    }

    void CommunityPage::onGetCommunityPostsFinished(bool success, const QList<CommunityPost> &posts, const QString &error) {
        clearPostsLayout();

        if (success)
        {
            if (posts.isEmpty())
            {
                QLabel* emptyMsg = new QLabel("社区还没有帖子，快来发布第一条吧！");
                emptyMsg->setAlignment(Qt::AlignCenter);
                emptyMsg->setStyleSheet("font-size: 16px; color: #777; margin-top: 50px;");
                postsLayout->addWidget(emptyMsg);
                return;
            }

            for (const CommunityPost &postData : posts)
            {
                PostCardWidget *card = new PostCardWidget(postData, ui->scrollAreaWidgetContents);

                connect(card, &PostCardWidget::cardClicked, this, &CommunityPage::handleCardClicked);
                connect(card, &PostCardWidget::likeClicked, this, &CommunityPage::handleLikeClickedOnCard);
                connect(card, &PostCardWidget::shareClicked, this, &CommunityPage::handleShareClickedOnCard);

                QFrame *line = new QFrame(this);
                line->setFrameShape(QFrame::HLine);
                line->setFrameShadow(QFrame::Sunken);
                line->setFixedHeight(1);
                line->setStyleSheet("QFrame { background-color: #e0e0e0; }");

                postsLayout->addWidget(line);

                postsLayout->addWidget(card);
                postCardMap[postData.id] = card;
            }

        }
        else
        {
            MessageBox::warning(this, "加载社区帖子失败: " + error);
            QLabel* errorMsg = new QLabel("加载帖子失败，请稍后重试。");
            errorMsg->setAlignment(Qt::AlignCenter);
            errorMsg->setStyleSheet("font-size: 16px; color: #cc0000; margin-top: 50px;");
            postsLayout->addWidget(errorMsg);
        }
        // postsLayout->addStretch(1); // Add stretch at the end if you want cards to not expand too much vertically
                                   // when few items are present, but usually AlignTop is enough.
    }

    void CommunityPage::onToggleLikePostFinished(bool success, int postId, int newLikesCount, bool isLiked, const QString &error)
    {
        if (success) {
            if (postCardMap.contains(postId)) {
                postCardMap[postId]->updateLikeState(newLikesCount, isLiked);
            }
        } else {
            MessageBox::warning(this, "操作失败: " + error);
        }
    }

    void CommunityPage::onRecordSharePostFinished(bool success, int postId, int newSharesCount, const QString &error)
    {
        if (success)
        {
            if (postCardMap.contains(postId)) {
                postCardMap[postId]->updateShareCount(newSharesCount);
            }
            QClipboard *clipboard = QApplication::clipboard();
            QString shareText = QString("我正在单词记忆App看到一个很棒的帖子！快来看看吧！帖子ID: %1").arg(postId);
            clipboard->setText(shareText);
            MessageBox::info(this, "帖子链接（示例）已复制到剪贴板！");
        }
        else
        {
            MessageBox::warning(this, "记录分享失败: " + error);
        }
    }


    void CommunityPage::handleCardClicked(int postId)
    {
        qDebug() << "Card clicked for post ID:" << postId;
        emit viewPostDetails(postId);
    }

    void CommunityPage::handleLikeClickedOnCard(int postId)
    {
        if (!UserManager::instance().isLoggedIn()) {
            MessageBox::warning(this, "请先登录才能点赞！");
            return;
        }
        serverhelper->toggleLikePost(postId, UserManager::instance().getUserId());
    }

    void CommunityPage::handleShareClickedOnCard(int postId)
    {
        qDebug() << "Share clicked for post ID:" << postId;

        serverhelper->recordSharePost(postId);
    }

    void CommunityPage::on_refreshButton_clicked()
    {
        loadPosts();
    }

} // namespace WordMemory
